
//初始化物料信息
var materialMap = {};
$(function(){

    var coId = $("#coId").val();
    //加载合同项目下拉框
    $.ajax({
        url: CONTEXT_PATH + "/contract/getContractListForCombo.do",
        type: "get",
        success: function (data) {
            var themecombo = "";
            if(data.length > 2){
                themecombo = "[{\"text\": \"--请选择--\", \"id\": \"\"},";
                themecombo += data.substring(1);
            }else{
                themecombo = "[{\"text\": \"--请选择--\", \"id\": \"\"}]";
            }
                themecombo = JSON.parse(themecombo);
            $("#contractList").combobox("loadData",themecombo);
            $("#contractList").combobox({
                valueField:'id',
                textField:'text',
                onSelect:function(node){
                    $('#coId').val(node.id);
                }
            });
            $("#contractList").combobox("setValue","");
        }
    });

    //初始化物料信息，若数据是导入情况，作为自动填入合同单价及合同剩余量基础数据
    $.ajax({
        url: CONTEXT_PATH + "/material/findMaterial.do?coId=" + coId,
        type: "post",
        dataType:'json',
        success: function (data) {
            for(var i=0;i<data.length;i++){
                var unitContractPrice = data[i].unitContractPrice == null?"":data[i].unitContractPrice;
                var leftCount = data[i].leftCount == null?"":data[i].leftCount;
                materialMap[data[i].materialInfo] = unitContractPrice + "," + leftCount;
            }
        }
    });

    //初始化动态表格
    $("#activeTableForPurchaseDetail").dyActiveTable({
        idField: 'purdId',
        idFieldWidth: 60,
        index:"序号",
        columns: [
            {field: 'materialName', title: '材料名称', width: 120, height: 30, type: 'text', option: 'required:true, validType:\'length[1,18]\', prompt:\'请输入材料名称\', valueField:\'maId\', textField:\'materialInfo\', onChange: function(v,o){' +
                'var url = CONTEXT_PATH + \'/material/findMaterial.do?materialName=\' + v + \'&coId=\'+ $(\'#coId\').val();' +
                '$(this).combobox(\'reload\', url)' +
                '},' +
                'onSelect: function(material){' +
                    'if(material != null){' +
                        'setMaterialValue(this, material);' +
                        '$.parser.parse(this);  ' +
                    '}' +
                '}', class: 'easyui-combobox'},
            {field: 'brand', title: '材料品牌', width: 120, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入品牌\'', class: 'easyui-textbox'},
            {field: 'standardType', title: '规格型号', width: 120, height: 30, type: 'text', option: 'required:true,validType:\'length[1,88]\', prompt:\'请输入规格型号\''},
            {field: 'technicalParameter', title: '技术参数', width: 120, height: 30, type: 'text', option: 'validType:\'length[1,88]\', prompt:\'请输入技术参数\'', class: 'easyui-textbox'},
            {field: 'meteringUnit', title: '计量单位', width: 120, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入计量单位\''},
            {field: 'unitContractPrice', title: '合同单价(元)', width: 120, height: 30, type: 'text'},
            {field: 'unitPrice', title: '采购单价(元)', width: 120, height: 30, type: 'text', option: 'required:true,validType:[\'floatOrInt\', \'length[1,18]\'], prompt:\'请输入采购单价\''},
            {field: 'purdNum', title: '请购数量', width: 120, height: 30, type: 'text', option: 'required:true,validType:[\'floatOrInt\', \'length[1,18]\'], prompt:\'请输入请购数量\''},
            {field: 'leftCount', title: '合同剩余量', width: 120, height: 30, type: 'text'},
            /*{field: 'characterization', title: '项目特性描述', width: 120, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入项目特性描述\''},
            {field: 'explain', title: '要求说明', width: 120, height: 30, type: 'text', option: 'validType:[\'length[1,88]\'], prompt:\'请输入要求说明\''},
            {field: 'belongSystem', title: '所属系统', width: 120, height: 30, type: 'text', option: 'validType:[\'length[1,88]\'], prompt:\'请输入所属系统\''},*/
            {field: 'reqRemark', title: '请购备注', width: 120, height: 30, type: 'text', option: 'validType:[\'length[1,188]\'], prompt:\'请输入请购备注\''},
            {field: 'purdTotalPrice', isInput: false, calculate: "multiply", calculateColumns: ['unitPrice','purdNum'], title: '合计金额(元)', width: 120, height: 30, type: 'text', class: ''}
        ],
        beforeRemove: removeLine
    });

    //加载请购清单的数据
    var data = {
        dataList: purchaseDetailList,
        editable: true
    };
    $("#activeTableForPurchaseDetail").dyActiveTable("loadData", data);

    //保存按钮点击事件
    $('#optionPurchaseDetail').bind('click', function(){
        doOptionPurchaseDetailMethod();
    })

    //模板下载点击事件
    $('#downloadBtn').bind('click', function(){
        downloadTemple();
    })

    //清空按钮点击事件
    $('#emptyTable').bind('click', function(){
        $("#activeTableForPurchaseDetail").dyActiveTable("removeLine");
    })

    //导入确定按钮点击事件
    $('#importBtn').bind('click', function(){
        //获取easyui中的input中的实际的file文件
        var file = $("input[name='importExcel']")[0].files ? $("input[name='importExcel']")[0].files[0] : "noFile";

        //判断是否在IE下而无法获取file
        if(file == "noFile"){
            $.messager.show({ title:'提示', msg: '本功能需要高级浏览器支持,请使用IE11及以上浏览器或其他非IE内核浏览器！', timeout:3000, showType:"slide" });
            return false;
        }
        //判断是否选择文件
        if(!file){
            $.messager.show({ title:'提示', msg: '请选择要上传的文件！', timeout:3000, showType:"slide" });
            return false;
        }
        //判断文件格式
        if(file.name.substring(file.name.lastIndexOf("."), file.name.length) != ".xlsx"){
            $.messager.show({ title:'提示', msg: '文件必须是xlsx类型的！', timeout:3000, showType:"slide" });
            return false;
        }
        readWorkbookFromLocalFile(file, parseData);
    })
});

/**
 * 根据名称模糊搜索后，将搜索的内容自动的补全到此行的各个选框中
 * @param combobox
 * @param material
 */
function setMaterialValue(nameInput, material){
    var $nameInput = $(nameInput);

    setTimeout(function(){
        $nameInput.combobox('setValue', material.materialName);
        $nameInput.combobox('setText', material.materialName);
    }, 100);
    var $standardType = $nameInput.closest("tr").find("input[textboxname='standardType']").textbox('setValue', material.standardType);
    var $brand = $nameInput.closest("tr").find("input[textboxname='brand']").textbox('setValue', material.brand);
    var $technicalParameter = $nameInput.closest("tr").find("input[textboxname='technicalParameter']").textbox('setValue', material.technicalParameter);
    var $meteringUnit = $nameInput.closest("tr").find("input[textboxname='meteringUnit']").textbox('setValue', material.meteringUnit);
    var $unitPrice = $nameInput.closest("tr").find("input[textboxname='unitPrice']").textbox('setValue', material.unitPrice);
    var $unitContractPrice = $nameInput.closest("tr").find("input[textboxname='unitContractPrice']").textbox('setValue', material.unitContractPrice);
    var $leftCount = $nameInput.closest("tr").find("input[textboxname='leftCount']").textbox('setValue', material.leftCount);
}

//初始化导入模板下载
function downloadTemple(){
    var aoa = [
        ['材料名称','材料品牌', '规格型号', '技术参数', '计量单位', '采购单价(元)', '请购数量', '请购备注'],
        ['道闸','泰德','TF-DF500S','','台', '800','30', '若无TF-DF550S可采用TF-DF100R代替'],
        ['光纤连接','达康', 'LIV_Udm25','','米', '5','500', '若无腾达AC11,可用其他品牌同芯数材料代替']
    ];
    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(aoa);

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '请购清单');

    if(isIEAll()){
        $.messager.show({ title:'提示', msg: '导入功能需要高级浏览器支持,其他非IE内核浏览器再下载模板进行导入操作！', timeout:3000, showType:"slide" });
        return false;
    }else{
        /* generate download */
        XLSX.writeFile(wb, "请购清单模板.xlsx");
    }
}

//从读取到的excel中取解析数据，插入到表格中
function parseData(workbook){
    var sheetNames = workbook.SheetNames; // 工作表名称集合
    var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
    var json = XLSX.utils.sheet_to_json(worksheet);
    action(function(){
        $.messager.progress({
            title: '提示',
            msg: '数据加载中, 请稍候...',
            text: '',
            interval:0
        });
    })
    action(function(json){
        if(json.length == 0){
            action(closeProgress, null, 500);
        }
        for(var i=0; i < json.length; i++){
            setTimeout((function(i, json){
                return function(){
                    var rowData = json[i];
                    var jsonForAdd = {};
                    jsonForAdd["materialName"] = rowData["材料名称"];
                    jsonForAdd["brand"] = rowData["材料品牌"];
                    jsonForAdd["standardType"] = rowData["规格型号"];
                    jsonForAdd["technicalParameter"] = rowData["技术参数"];
                    jsonForAdd["meteringUnit"] = rowData["计量单位"];
                    jsonForAdd["unitPrice"] = rowData["采购单价(元)"];
                    jsonForAdd["purdNum"] = rowData["请购数量"];
                    jsonForAdd["reqRemark"] = rowData["请购备注"];
                    var materialName = rowData["材料名称"];
                    var standardType = rowData["规格型号"];
                    if(null != materialName && null != standardType){
                        materialName = materialName.replace(/[\r\n]/g,"");
                        standardType = standardType.replace(/[\r\n]/g,"");
                        var materInfo = materialName + "(" + standardType + ")";
                        materInfo = materialMap[materInfo];
                        if(null != materInfo){
                            var materInfoArr = materInfo.split(",");
                            //合同单价
                            jsonForAdd["unitContractPrice"] = materInfoArr[0];
                            //合同剩余量
                            jsonForAdd["leftCount"] = materInfoArr[1];
                            //请购数量
                            var purdNum = rowData["请购数量"];
                            //合同类型，合同内的材料才做数量对比
                            var purType = $("#purType").val();
                            if("1" == purType){
                                if(null != purdNum && null != materInfoArr[1] && "" != materInfoArr[1]){
                                    //请购数量大于合同量则不予导入，并提示
                                    if(purdNum > materInfoArr[1]){
                                        $.messager.progress('close');
                                        $.messager.alert("系统提示", "第" + (i+1) + "条请购数量为 " + purdNum + " 已超过合同剩余量 " + materInfoArr[1] + ",请修改后重新导入!" );
                                        $("#activeTableForPurchaseDetail").dyActiveTable("removeLine");
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    var value = ((i + 1) / json.length * 100);
                    action(progressValue, value);
                    var param = [jsonForAdd, true]
                    $("#activeTableForPurchaseDetail").dyActiveTable("addLine", param);
                    if(i == json.length - 1){
                        $("#activeTableForPurchaseDetail").dyActiveTable("sortIndex");
                        action(closeProgress, null, 500);
                    }
                }
            })(i, json),i*100);
        }
    }, json);
}

function action(callback, param, time){
    setTimeout(callback(param), time);
}

/**
 * 更新进度条的显示值
 * @param value
 */
function progressValue(value){
    $.messager.progress("bar").progressbar("setValue", value);
    console.log("progressValue======>" + value);
}

/**
 * 关闭进度的显示
 */
function closeProgress(){
    $("#activeTableForPurchaseDetail").dyActiveTable("removeLine", [1, 1]);
    $.messager.progress('close');
}

// 读取本地excel文件
function readWorkbookFromLocalFile(file, callback) {
    var reader = new FileReader();
    //判断redaer的readAsBinaryString方法是否存在
    if(reader.readAsBinaryString){
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }else{
        reader.readAsArrayBuffer(file);
        reader.onload = function(e){
            var bytes = new Uint8Array(e.target.result);
            var length = bytes.byteLength;
            var binary = "";
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            var base64Str = btoa(binary);
            var workbook = XLSX.read(base64Str, {type: 'base64'});
            if(callback) callback(workbook);
        }.bind(this);
    }
}

/**
 * 执行保存操作方法
 */
function doOptionPurchaseDetailMethod(){
    var params = $("#operate_form").serialize();
    $("#operate_form").form("submit",{
        cache:false,
        data: params,
        url: CONTEXT_PATH + "/purchaseDetail/save.do",
        onSubmit:function() {
            var flag = $(this).form("validate");
            if(flag){
                preventSubmit(null, "optionPurchaseDetail");
            }
            return flag;
        },
        success:function(data) {
            var obj = JSON.parse(data);
            if(obj.code == "PC_002"){
                messager(obj);
                $("#optionPurchaseDetail").linkbutton('enable');
                //保存按钮点击事件
                $('#optionPurchaseDetail').bind('click', function(){
                    doOptionPurchaseDetailMethod();
                });
                return;
            }else{
                var url = CONTEXT_PATH + "/purchaseApply/index.do";
                saveJump(obj,url);
            }

        }
    });
}

/**
 * 删除一行
 * @param row
 */
function removeLine(row){
    //验证是否是原有的数据，可以从库中删除
    if(!row || !row.purdId || row.purdId == "" ){
        return true;
    }
    //带有purdId，可以删除
    if(row && row.purdId){
        $.messager.confirm('删除提示', '您确定要删除该条数据吗？此操作会永久删除此条数据', function (r) {
            if (r) {
                console.log("删除一行:purdId=" + row.purdId);
                $.ajax({
                    async: false,
                    url: CONTEXT_PATH + "/purchaseDetail/del.do?purdId=" + row.purdId,
                    type: "get",
                    dataType: "json",
                    success: function (data) {
                        messager(data);
                        //删除页面上显示的数据
                        $("#activeTableForPurchaseDetail").dyActiveTable("removeLineById", row.purdId);
                    }
                })
            }
        });
    }
    return false;
}